import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { FormInstance } from 'antd/lib/form';
import { Modal, Button, Form, message, Input, Select, Upload } from 'antd';
import PropTypes from 'prop-types';
import { PlusOutlined } from '@ant-design/icons';
import { fromJS } from 'immutable';
import { getToken } from '@/utils';
import { getOptAuthHeaders } from '@/utils/common';

const FormItem = Form.Item;
const { TextArea } = Input;
const mapStateToProps = (state: any) => ({
  DriverMng: state.DriverMng,
});
class HandleModal extends PureComponent<any, any> {
  formRef = React.createRef<FormInstance>();
  static contextTypes = {
    permissions: PropTypes.array,
    dicData: PropTypes.object,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      fileList: [],
      uploadMessage: {
        statusCode: '0',
        statusMessage: '',
      },
      fleetList: [],
      vinList: [],
    };
  }

  componentDidUpdate(prevProps: any) {
    const { modalVisible, formData } = this.props;
    if (modalVisible && modalVisible !== prevProps.modalVisible) {
      this.formRef &&
        typeof formData.sid === 'number' &&
        this.formRef.current?.setFieldsValue({
          ...formData,
          fleetSid: formData.fleetSid,
          // vinList: formData.vehicleList?.map(t => t.vin) ?? [],
        });
      this.getFleetList();
      if (formData && formData.facePictureUrl) {
        this.setState({
          fileList: [
            {
              uid: -1,
              url: formData.facePictureUrl,
            },
          ],
        });
      }
    }
  }

  getFleetList = () => {
    const { formData, dispatch } = this.props;
    dispatch({
      type: 'FleetMng/getData',
      payload: {
        url: '/msalcohollock/fleet/user/list',
      },
      callback: (res: any) => {
        const fleetList =
          res.data?.map((t: { fleetSid: any; fleetName: any }) => ({
            value: t.fleetSid,
            label: t.fleetName,
          })) ?? [];
        this.setState({
          fleetList: fleetList,
        });
        if (typeof formData.sid !== 'number' && fleetList.length) {
          this.formRef &&
            this.formRef.current?.setFieldsValue({
              fleetSid: fleetList[0].value,
            });
        }
        if (fleetList.length)
          this.getVinList(formData.sid === 'number' ? formData.fleetSid : fleetList[0].value);
      },
    });
  };

  handleSubmit = () => {
    this.formRef.current?.submit();
  };

  onFinish = (values: any) => {
    //     1	name
    // 2	phoneNumber
    // 3	fleetSid
    // 4	vinList
    // 5	face_picture_url
    const { dispatch, formData, freshPage } = this.props;
    const { uploadMessage } = this.state;
    if (uploadMessage.statusCode !== '0') return;
    const isEdit = typeof formData.sid === 'number';
    let postData = {
      ...values,
      face_picture_url: uploadMessage.data,
    };
    let dType = 'DriverMng/postObj';
    const url = !isEdit ? '/msalcohollock/driver' : `/msalcohollock/driver/${formData.sid}`;
    if (typeof formData.sid === 'number') {
      postData.sid = formData?.sid;
      dType = 'DriverMng/putObj';
    }
    this.setState({
      loading: true,
    });
    dispatch({
      type: dType,
      payload: {
        url,
        ...postData,
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          message.success(isEdit ? '编辑成功' : '新增成功');
          this.close();
          freshPage();
        }
      },
    }).finally(() =>
      this.setState({
        loading: false,
      }),
    );
  };

  close = () => {
    const { closeModal } = this.props;
    this.setState({
      fileList: [],
      uploadMessage: {
        statusCode: '0',
        statusMessage: '',
      },
    });
    this.formRef.current && this.formRef.current.resetFields();
    closeModal();
  };
  handleUrlChange = info => {
    let { fileList } = info;
    fileList = fileList.slice(-1);
    if (info.file.status === 'done' && info.file.response) {
      message.success(`${info.file.name} 上传成功`);
      this.setState({
        uploadMessage: info.file.response,
      });
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败`);
    } else if (!info.file.status) {
      this.setState({
        fileList: [],
      });
      return;
    }
    this.setState({ fileList: fileList });
  };
  beforeUpload = (file: any) => {
    if (file.type === 'image/jpeg' || file.type === 'image/png') {
      if (file.size / 1024 / 1024 > 5) {
        message.error('图片大小不能大于5MB!');
        return false;
      }
      return true;
    } else {
      message.error('请上传JPG或PNG格式图片！');
      return false;
    }
  };
  handleCancel = () => this.setState({ previewVisible: false });
  handlePreview = file => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  };
  removeList = (fileList: any, file: any) => {
    const newList = fromJS(fileList).toJS();
    const i = newList.findIndex(e => e.uid === file.uid);
    if (i >= 0) {
      newList.splice(i, 1);
    }
    return newList;
  };
  // 文件删除
  handleRemove = (file: any) => {
    const { formData } = this.props;
    if (formData && formData.monitorCount > 0) {
      message.warning('司机已激活监控，不能修改照片!');
      return false;
    }
    const { fileList } = this.state;
    const newList = this.removeList(fileList, file);
    this.setState({ fileList: newList });
  };

  handleFormChange = data => {
    if (typeof data.fleetSid === 'number') {
      this.formRef &&
        this.formRef.current?.setFieldsValue({
          vinList: [],
        });
      this.getVinList(data.fleetSid);
    }
  };
  getVinList = (sid: number) => {
    const { dispatch, formData } = this.props;
    const params = { sid: sid, vin: '' };
    dispatch({
      type: 'FleetMng/getData',
      payload: {
        url: '/msalcohollock/fleet/vehicle/vin/list',
        ...params,
      },
      callback: (res: any) => {
        const formDataVinList = formData.vehicleList?.map(t => t.vin) ?? [];
        const vinList =
          res.data?.map((t: any) => ({
            value: t.vin,
            label: t.vin,
          })) ?? [];
        this.setState({
          vinList: vinList.filter(t => !formDataVinList.includes(t.value)),
        });
      },
    });
  };
  render() {
    const { formData, modalVisible } = this.props;
    const { loading, previewVisible, previewImage, uploadMessage, fleetList, vinList, fileList } =
      this.state;
    const isActived = formData?.monitorCount > 0;

    const footer = (
      <div>
        <Button size="small" onClick={this.close}>
          取消
        </Button>
        <Button size="small" loading={loading} onClick={this.handleSubmit} type="primary">
          确定
        </Button>
      </div>
    );
    let title = formData.sid ? '编辑司机' : '新增司机';

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: {
          span: 6,
          // offset: 4,
        },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: {
          span: 14,
        },
        md: { span: 16 },
      },
    };
    const domain = window.g.url;
    const url = '/msalcohollock/driver/photo/upload';
    const str = `${domain}${url}/${formData.sid ?? 0}`;
    const uploadButton = (
      <button
        style={{
          border: 0,
          background: 'none',
        }}
        type="button"
      >
        <PlusOutlined />
        <div
          style={{
            marginTop: 8,
          }}
        >
          {fileList.length ? '更新人脸图片' : '上传清晰人脸图片'}
        </div>
      </button>
    );
    return (
      <Modal title={title} footer={footer} visible={modalVisible} width={700} onCancel={this.close}>
        <Form
          onValuesChange={this.handleFormChange}
          // onFieldsChange={this.handleFormChange}
          style={{ marginTop: 12 }}
          ref={this.formRef}
          onFinish={this.onFinish}
        >
          <FormItem
            {...formItemLayout}
            label="司机姓名"
            colon={false}
            name="name"
            // rules={[
            //   {
            //     required: true,
            //     message: '只能输入中英文及数字，特殊字符,最长可输入50个字符',
            //     pattern: /^[\u4e00-\u9fa5a-zA-Z0-9\s\w]+$/,
            //     whitespace: true,
            //   },
            // ]}
            rules={[{ required: true, message: '不能输入空字符', pattern: /^\S+$/ }]}
          >
            <Input placeholder="请输入司机姓名" maxLength={50} />
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="手机号"
            colon={false}
            name="phoneNumber"
            rules={[
              {
                required: true,
                message: '请输入合规的手机号',
                pattern: /^(13[0-9]|14[5-9]|15[0-3,5-9]|16|17[0-8]|18[0-9]|19[8,9])\d{8}$/,
                whitespace: true,
              },
            ]}
          >
            <Input placeholder="请输入手机号" maxLength={11} />
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="关联车队"
            colon={false}
            name="fleetSid"
            rules={[{ required: false, message: '请选择车队' }]}
          >
            <Select
              placeholder="请选择关联的车队"
              options={fleetList}
              disabled={formData.vehicleList?.length ?? false}
              showSearch
            />
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="关联车辆"
            colon={false}
            name="vinList"
            rules={[{ required: false, message: '请选择车辆' }]}
          >
            <Select placeholder="请选择关联的车辆" options={vinList} mode="multiple" showSearch />
          </FormItem>
          <FormItem {...formItemLayout} label="人脸照片" colon={false} name="facePictureUrl">
            <Upload
              disabled={isActived}
              action={str}
              // maxCount={1}
              method="post"
              headers={{ OptAuthorization: `${getToken()}`, ...getOptAuthHeaders() }}
              accept=".png, .gif, .jpeg, .jpg, .bmp"
              listType="picture-card"
              fileList={this.state.fileList}
              onPreview={this.handlePreview}
              onChange={this.handleUrlChange}
              beforeUpload={this.beforeUpload}
              onRemove={this.handleRemove}
              iconRender={() => <p>dddd</p>}
            >
              {this.state.fileList.length >= 2 || isActived ? null : uploadButton}
            </Upload>
            <p>
              <span> {isActived ? '司机已激活监控，不能修改照片' : ''}</span>
            </p>
            <span>* 请上传光线充足、清晰的正脸照片，照片中只能出现一张人脸</span>
            {uploadMessage?.statusCode === '0' ? null : (
              <div style={{ fontSize: 12, color: 'red' }}>
                用户照片不合格,{uploadMessage?.statusMessage}
              </div>
            )}
          </FormItem>
        </Form>
        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
          <img alt="" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </Modal>
    );
  }
}
export default connect(mapStateToProps)(HandleModal);
